package com.tzkyzj.tiremanagersystem.network;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import java.util.HashSet;
import java.util.Set;

public class SessionManager {
    private static final String TAG = "SessionManager";
    private static final String PREF_NAME = "session_prefs";
    private static final String KEY_COOKIES = "cookies";

    private static SessionManager instance;
    private SharedPreferences sharedPreferences;

    private SessionManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }

    public static synchronized SessionManager getInstance(Context context) {
        if (instance == null) {
            instance = new SessionManager(context.getApplicationContext());
        }
        return instance;
    }

    /**
     * 保存 Cookie
     */
    public void saveCookies(Set<String> cookies) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putStringSet(KEY_COOKIES, cookies);
        editor.apply();
        Log.d(TAG, "保存 Cookie: " + cookies.size() + " 个");
    }

    /**
     * 获取保存的 Cookie
     */
    public Set<String> getCookies() {
        return sharedPreferences.getStringSet(KEY_COOKIES, new HashSet<>());
    }

    /**
     * 清除所有 Cookie
     */
    public void clearCookies() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_COOKIES);
        editor.apply();
        Log.d(TAG, "清除所有 Cookie");
    }

    /**
     * 调试 Cookie 状态
     */
    public void debugCookies() {
        Set<String> cookies = getCookies();
        Log.d(TAG, "=== Cookie 状态 ===");
        Log.d(TAG, "Cookie 数量: " + cookies.size());
        for (String cookie : cookies) {
            Log.d(TAG, "Cookie: " + cookie);
        }
        Log.d(TAG, "=== Cookie 状态结束 ===");
    }
}